package org.demo.config.extendSqlMethods;

import com.baomidou.mybatisplus.core.injector.AbstractMethod;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.toolkit.sql.SqlScriptUtils;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlSource;

/**
 * @author yexi
 */
public class UpdateClickHouse extends AbstractMethod {

    /**
     * 修改自
     *
     * @see com.baomidou.mybatisplus.core.injector.methods.Update
     */
    @Override
    public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
        ExtendSqlMethod sqlMethod = ExtendSqlMethod.UPDATE_CLICKHOUSE;
        String sql = String.format(sqlMethod.getSql(),
                tableInfo.getTableName(),
                this.sqlSet(true, true, tableInfo, true, ENTITY, ENTITY_DOT),
                super.sqlWhereEntityWrapper(true, tableInfo),
                super.sqlComment());
        SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, modelClass);
        return this.addUpdateMappedStatement(mapperClass, modelClass, sqlMethod.getMethod(), sqlSource);
    }

    /**
     * SQL 更新 set 语句
     *
     * @param logic  是否逻辑删除注入器
     * @param ew     是否存在 UpdateWrapper 条件
     * @param table  表信息
     * @param alias  别名
     * @param prefix 前缀
     * @return sql
     */
    @Override
    protected String sqlSet(boolean logic, boolean ew, TableInfo table, boolean judgeAliasNull, final String alias,
                            final String prefix) {
        String sqlScript = table.getAllSqlSet(logic, prefix);
        if (judgeAliasNull) {
            sqlScript = SqlScriptUtils.convertIf(sqlScript, String.format("%s != null", alias), true);
        }
        if (ew) {
            sqlScript += NEWLINE;
            sqlScript += SqlScriptUtils.convertIf(SqlScriptUtils.unSafeParam(U_WRAPPER_SQL_SET),
                    String.format("%s != null and %s != null", WRAPPER, U_WRAPPER_SQL_SET), false);
        }
        sqlScript = this.convertSet(sqlScript);
        return sqlScript;
    }

    /**
     * 不加 <set></set> 标签，并且去除最后一个逗号
     *
     * @see SqlScriptUtils#convertSet(String) 不可以使用。因为会加上 <set></set> 标签，而clickhouse的更新语句并没有。
     */
    private String convertSet(final String sqlScript) {
        return SqlScriptUtils.convertTrim(sqlScript, null, null, null, ",");
    }

}